package com.designoutput.utils
{
	import flash.system.Capabilities;

	public class Unit
	{
		private static var DPI:Number = 96;
				
		public static const INCHES:Unit = new Unit("Inches", "in", function(value:Number):Number { return value; }, function(value:Number):Number { return value; });
		public static const MILLIMETERS:Unit = new Unit("Millimeters", "mm", function(value:Number):Number { return value/25.4; }, function(value:Number):Number { return value*25.4; });
		public static const CENTIMETERS:Unit = new Unit("Centimeters", "cm", function(value:Number):Number { return value/2.54; }, function(value:Number):Number { return value*2.54; });
		public static const POINTS:Unit = new Unit("Points", "pt", function(value:Number):Number { return value/72; }, function(value:Number):Number { return value*72; });
		public static const PICAS:Unit = new Unit("Picas", "pica", function(value:Number):Number { return value/12; }, function(value:Number):Number { return value*12; });
		public static const PIXELS:Unit = new Unit("Pixels", "px", function(value:Number):Number { return value/DPI; }, function(value:Number):Number { return value*DPI; });
		
		private static var _units:Vector.<Unit> = new <Unit>[
			INCHES,
			MILLIMETERS,
			CENTIMETERS,
			POINTS,
			PICAS,
			PIXELS
		];
		
		public static function getUnitByName(name:String):Unit {
			for each(var unit:Unit in _units)
			{
				if(unit.name == name)
					return unit;
			}
			return null;
		}
		
		public static function getUnitBySymbol(symbol:String):Unit {
			for each(var unit:Unit in _units)
			{
				if(unit.symbol == symbol)
					return unit;
			}
			return null;
		}
		
		
		
		private var _name:String;
		private var _symbol:String;
		
		private var _toDefaultUnitFunction:Function;
		private var _fromDefaultUnitFunction:Function;
					
		public function Unit(name:String, symbol:String, toDefaultUnitFunction:Function, fromDefaultUnitFunction:Function):void {
			_name = name;
			_symbol = symbol;
			_toDefaultUnitFunction = toDefaultUnitFunction;
			_fromDefaultUnitFunction = fromDefaultUnitFunction;
		}
		
		public function get name():String {
			return _name;
		}
		
		public function get symbol():String {
			return _symbol;
		}
		
		public function toDefaultUnit(value:Number):Number {
			return _toDefaultUnitFunction(value);
		}
		
		public function fromDefaultUnit(value:Number):Number {
			return _fromDefaultUnitFunction(value);
		}
		
		public function format(value:Number):String {
			return value.toString() + _symbol;
		}
	}
}